package com.jvm.interpreter.instruction;

import com.jvm.Utils;
import com.jvm.classfile.model.CpInfo;
import com.jvm.classfile.model.Field;
import com.jvm.classfile.model.Instance;
import com.jvm.interpreter.Frame;
import com.jvm.interpreter.Instruction;

/**
 * @program: diy_simple_jvm
 * @description:
 * @author: CaoYong
 * @create: 2021-07-09 16:21
 **/
public class GetFieldInst implements Instruction {

    final String clazz;
    final String name;
    final String descriptor;

    GetFieldInst(String clazz, String name, String descriptor) {
        this.clazz = clazz;
        this.name = name;
        this.descriptor = descriptor;
    }

    @Override
    public void eval(Frame frame) {
        final Instance self = frame.popRef();
        final Field field = self.getField(name, descriptor);
        field.get(frame);

        frame.pc += offset();
    }

    @Override
    public int offset() {
        return 3;
    }

    static GetFieldInst parse(java.io.DataInputStream dis, CpInfo[] cp) throws java.io.IOException {
        final int gffi = dis.readUnsignedShort();
        return new GetFieldInst(Utils.getClassNameFromFieldRef(cp, gffi), Utils.getNameFromFieldRef(cp, gffi),
                Utils.getDescriptorFromFieldRef(cp, gffi));
    }
}
